package main

import "fmt"

// 如何对字符串进行反转
// 引申：如何对单词进行反转

func main() {
	str := "abcdefg"
	fmt.Println(reverseStr(str))

	str = "how dare you"
	fmt.Println(swapWords(str))
}

// 方法1：临时变量法

// 方法2：直接交换法
func reverseStr(str string) string {
	ch := []rune(str)
	for i, j := 0, len(str)-1; i < j; i, j = i+1, j-1 {
		ch[i] = ch[i] ^ ch[j]
		ch[j] = ch[i] ^ ch[j]
		ch[i] = ch[i] ^ ch[j]
	}

	return string(ch)
}

func reversePart(ch []rune, front, end int) {
	for front < end {
		ch[front] = ch[front] ^ ch[end]
		ch[end] = ch[front] ^ ch[end]
		ch[front] = ch[front] ^ ch[end]
		front++
		end--
	}
}

func swapWords(str string) string {
	ch := []rune(str)
	ll := len(ch)
	reversePart(ch, 0, ll-1)
	begin := 0
	for i := 1; i < ll; i++ {
		if ch[i] == ' ' {
			reversePart(ch, begin, i-1)
			begin = i + 1
		}
	}
	reversePart(ch, begin, ll-1)
	return string(ch)
}
